package org.example.validate;

import org.aopalliance.intercept.MethodInvocation;
import org.springframework.security.access.AccessDecisionVoter;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.prepost.PreInvocationAttribute;
import org.springframework.security.access.prepost.PreInvocationAuthorizationAdvice;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import java.util.Collection;

/**
 * 自定义投票器
 */
public class MyAccessVoter implements AccessDecisionVoter<MethodInvocation> {

    private static final String superAuthority = "chen_";

    private final PreInvocationAuthorizationAdvice preAdvice;

    public MyAccessVoter(PreInvocationAuthorizationAdvice pre){
        this.preAdvice=pre;
    }

    @Override
    public boolean supports(ConfigAttribute attribute) {
        return true;
    }
    @Override
    public boolean supports(Class clazz) {
        return true;
    }

    @Override
    public int vote(Authentication authentication, MethodInvocation method,
                    Collection<ConfigAttribute> attributes) {

        // 隐藏字符串
//        FilterInvocation filterInvocation = (FilterInvocation) object;
//        String hiddenParameter = filterInvocation.getHttpRequest().getParameter(hiddenUrl);
//        if (hiddenParameter != null){
//            return ACCESS_GRANTED;
//        }

        //没有权限默认拒绝
        if (authentication == null){
            return ACCESS_DENIED;
        }

        //匿名用户 不允许
        if (authentication instanceof AnonymousAuthenticationToken) {
            return ACCESS_DENIED;
        }

        //获取数据库配置权限
        //如果权限中有一条符合 默认超管配置的  直接返回成功
        Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
        for (GrantedAuthority authority : authorities) {
            if(authority.getAuthority().equals(superAuthority)){
                return ACCESS_GRANTED;
            }
        }

        // 以下 原先逻辑的不变动
        PreInvocationAttribute preAttr = findPreInvocationAttribute(attributes);
        if (preAttr == null) {
            // No expression based metadata, so abstain
            return ACCESS_ABSTAIN;
        }

        boolean allowed = preAdvice.before(authentication, method, preAttr);

        return allowed ? ACCESS_GRANTED : ACCESS_DENIED;
    }

    private PreInvocationAttribute findPreInvocationAttribute(
            Collection<ConfigAttribute> config) {
        for (ConfigAttribute attribute : config) {
            if (attribute instanceof PreInvocationAttribute) {
                return (PreInvocationAttribute) attribute;
            }
        }
        return null;
    }
}
